#include "syncpublish.h"

using namespace sync_publish_tools;

SyncPublish::SyncPublish()
    :MqttClient()
{
    m_cb.setPublish(this);
}

bool SyncPublish::activate()
{
    m_client = new mqtt::client(m_address, m_clientId, &m_persist);
    m_client->set_callback(m_cb);

    m_connOpts.set_keep_alive_interval(20);
    m_connOpts.set_clean_session(true);

    try
    {
        std::cout << "Connecting..." << std::flush;
        m_client->connect(m_connOpts);
        std::cout << "OK" << std::endl;

        m_client->subscribe("controllcommand", m_QOS);
    }
    catch (const mqtt::persistence_exception& exc)
    {
        std::cerr << "Persistence Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << std::endl;
        return false;
    }
    catch (const mqtt::exception& exc)
    {
        std::cerr << "Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << std::endl;
        return false;
    }
    return true;
}

bool SyncPublish::deactivate()
{
    try
    {
        std::cout << "Disconnecting..." << std::flush;
        m_client->disconnect();
        std::cout << "OK" << std::endl;
    }
    catch (const mqtt::persistence_exception& exc)
    {
        std::cerr << "Persistence Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << std::endl;
        return false;
    }
    catch (const mqtt::exception& exc)
    {
        std::cerr << "Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << std::endl;
        return false;
    }

    return true;
}

void SyncPublish::sendMessage(std::string message)
{
    // First use a message pointer.
    try
    {
        mqtt::message_ptr pubmsg = std::make_shared<mqtt::message>(message);
        pubmsg->set_qos(m_QOS);
        m_client->publish(m_topic, pubmsg);
    }
    catch (const mqtt::exception& exc)
    {
        std::cerr << "Error: " << exc.get_message() << " ["
                  << exc.get_reason_code() << "]" << std::endl;
        return;
    }

}

void SyncPublish::sendMessage(const QString& topic, std::string message)
{
    try
    {
        mqtt::message_ptr pubmsg = std::make_shared<mqtt::message>(message);
        pubmsg->set_qos(m_QOS);
        m_client->publish(topic.toStdString(), pubmsg);
    }
    catch (const mqtt::exception& exc)
    {
        std::cerr << "Error: " << exc.get_message() << " ["
                  << exc.get_reason_code() << "]" << std::endl;
        return;
    }
}

void SyncPublish::sendCommandControl(std::string send_str, std::string& responce_str)
{
//    std::string test_str = "test/cmd";
    QByteArray ba(send_str.data(), send_str.size());
    QString responce;
    emit commandControl(ba, &responce);
    responce_str = responce.toStdString();
}



